package com.goodboys.controller;

import com.goodboys.base.controller.BaseController;
import com.goodboys.base.entity.BaseReqBean;
import com.goodboys.base.resp.Response;
import com.goodboys.base.utils.RedisClient;
import com.goodboys.entity.User;
import com.goodboys.service.UserService;
import com.goodboys.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by CJ on 2018-05-19.
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User>{

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RedisClient redisClient;

//    private Response response  = new Response();

    @PostMapping("/update")
    @ResponseBody
    public Response update(User user,@RequestParam(value = "imgFile",required = false) MultipartFile imgFile,HttpServletRequest request){
        Response response = new Response();
        if(StringUtils.isEmpty(user.getId())) return response.failure("用户id为空，请重试。。。");
        if(!JwtUtils.isPermission(user.getId(),request)) return  response.failure("他人信息，不可更新。。");
        try {
            Map result = userService.updateUser(user,imgFile);
            return getRetunResult(result,response);
        } catch (Exception e) {
            logger.error("更新用户失败，请重试。。。");e.printStackTrace();
            return response.failure("更新用户失败，请重试。。。");
        }
    }

    @GetMapping("/nearUsers")
    @ResponseBody
    public Response nearUsers(BaseReqBean baseReqBean){
        Response response = new Response();
        try {
            Map result = userService.nearUsers(baseReqBean);
            return  getRetunPageList(result,response);
        } catch (Exception e) {
            logger.error("查询附近用户失败，请重试。。。");e.printStackTrace();
            return response.failure("查询附近用户失败，请重试。。。");
        }
    }

    @PostMapping("/logout")
    @ResponseBody
    public Response logout(@Param("id") String id, HttpServletRequest request) throws UnsupportedEncodingException {
        Response response = new Response();
        request.setCharacterEncoding("utf-8");
        String authHeader = request.getHeader("authorization");
        redisClient.delete("token:" + authHeader);
        return response.success("退出成功。。。");
    }
}
